export {
	socket
}
import DB from 'utils/sqlite.js'
var socket = {
	is_open_socket: false, //避免重复连接
	url: "", //地址
	data: "",
	uid: "",
	//心跳检测
	timeout: 0, //多少秒执行检测
	heartbeatInterval: null, //检测服务器端是否还活着
	reconnectTimeOut: null, //重连之后多久再次重连

	constructor(url, time, uid) {
		socket.is_open_socket = false //避免重复连接
		socket.url = url //地址
		socket.data = null
		socket.uid = uid
		//心跳检测
		socket.timeout = time //多少秒执行检测
		socket.heartbeatInterval = null //检测服务器端是否还活着
		socket.reconnectTimeOut = null //重连之后多久再次重连

		try {
			return socket.connectSocketInit()
		} catch (e) {
			console.log('catch');
			socket.is_open_socket = false
			socket.reconnect();
		}
	},

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		socket.socketTask = uni.connectSocket({
			url: socket.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return socket.socketTask
			},
		});
		socket.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			clearTimeout(socket.reconnectTimeOut)
			clearTimeout(socket.heartbeatInterval)
			socket.is_open_socket = true;

			socket.data = {
				userId: Number(socket.uid),
				msgType: 600
			}
			socket.send(JSON.stringify(socket.data));

			socket.start();
			// 注：只有连接正常打开中 ，才能正常收到消息
			socket.socketTask.onMessage((res) => {
				console.log(res.data)
				if (JSON.parse(res.data).msgType == 611) {
					let record = JSON.parse(res.data);

					let chatRecordsSql =
						`'${1}','${record.fromId}','${record.toId}','${record.msgType}','${record.message}','${record.createTime}'`;
					let chatRecordsCondition =
						"'type','fromId','toId','msgType','message','createTime'";

					DB.insertTableData("chatRecords_" + uni.getStorageSync("userId"),
							chatRecordsSql,
							chatRecordsCondition)
						.then(res => {
							console.log("chatRecords新增数据成功");
						})
						.catch(error => {
							console.log("chatRecords新增数据失败", error);
						});

					let chatListSql =
						`'${record.fromId}','${1}','${record.msgType}','${record.message}','${record.createTime}'`;
					let chatListCondition = "'id','type','msgType','lastMessage','createTime'";
					DB.insertOrReplaceData("chatList_" + uni.getStorageSync("userId"), chatListSql,
							chatListCondition)
						.then(res => {
							console.log("chatList新增数据成功");
						})
						.catch(error => {
							console.log("chatList新增数据失败", error);
						});
					let count = Number(uni.getStorageSync("unReadCount" + record.fromId));
					if (count != null) {
						uni.setStorageSync("unReadCount" + record.fromId, count + 1);
					} else {
						uni.setStorageSync("unReadCount" + record.fromId, 1);
					}
				} else if (JSON.parse(res.data).msgType == 900) {
					uni.navigateTo({
						url:"/pages/contact/vedio/vedio?type='from'&fromId="+JSON.parse(res.data).toId+"&toId="+JSON.parse(res.data).fromId
					})
				}
			});
		})
		// 监听连接失败，这里代码我注释掉的原因是因为如果服务器关闭后，和下面的onclose方法一起发起重连操作，这样会导致重复连接
		// uni.onSocketError((res) => {
		// 	console.log('WebSocket连接打开失败，请检查！');
		// 	socket.is_open_socket = false;
		// 	socket.reconnect();
		// });
		// 这里仅是事件监听【如果socket关闭了会执行】
		socket.socketTask.onClose(() => {
			console.log("已经被关闭了")
			socket.is_open_socket = false;
			socket.reconnect();
		})
	},

	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		socket.socketTask.send({
			data: value,
			async success() {
				console.log("消息发送成功");
			},
		});
	},
	//开启心跳检测
	start() {
		socket.heartbeatInterval = setInterval(() => {
			socket.data = {
				userId: Number(socket.uid),
				msgType: 600
			}
			console.log(socket.data)
			socket.send(JSON.stringify(socket.data));
		}, socket.timeout)
	},
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(socket.heartbeatInterval)
		//如果不是人为关闭的话，进行重连
		if (!socket.is_open_socket) {
			socket.reconnectTimeOut = setTimeout(() => {
				socket.connectSocketInit();
			}, 3000)
		}
	},
	//外部获取消息
	getMessage(callback) {
		socket.socketTask.onMessage((res) => {
			return callback(res)
		})
	}

}